import _axios from "../../axios";
import {Message} from "element-ui";
import {securityApi} from "./securityApi";
import {security_const} from "./constant";
import {securityStore} from "./observable";
import lodash from 'lodash/core'
/*控制xhr 附加 token */
_axios.interceptors.request.use(async requestConfig => {
    let oauthToken = securityStore.observe.oauthToken
    if (!lodash.isEmpty(oauthToken)) {
      // 检查token过期时间
      if ((new Date()).getTime() >= oauthToken[security_const.expired_at]) {
        Message({message: 'token失效，正在重新获取，请稍后重试', type: 'warning', duration: 3000})
        oauthToken = await securityApi.refresh({'refresh_token': oauthToken[security_const.refresh_token]})
        securityStore.mutation.changeOauthToken(oauthToken)
      }
      requestConfig.headers['Authorization'] = security_const.token_type + " " + oauthToken.access_token
    }
    return requestConfig
  }, error => {
    return Promise.reject(error)
  }
)
_axios.interceptors.response.use(responseData => {
    return responseData;
  }, error => {
    if(error.config.url!=securityApi.securityUrl.LOGOUT){
      if (error.response) {
        const resStatus = error.response.status||''
        const resErrMsg = error.response.data.error_description||'';
        if (resStatus === 401) {
          Message.error('您的授权错误！' + resErrMsg)
        } else if (resStatus === 403) {
          Message.error('您无该操作的权限!' + resErrMsg)
        }
      }
    }
    return Promise.reject(error)
  }
)
